package com.itheima.service.impl;

import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.dto.EditNumberByOrderDateDTO;
import com.itheima.pojo.entity.OrderSetting;
import com.itheima.pojo.vo.OrderSettingVO;
import com.itheima.service.OrderService;
import com.itheima.service.OrderSettingService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Override
    public void download(HttpServletResponse response) {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=ordersetting_template.xlsx");

        // 获取模板输入流
        InputStream resourceAsStream = this.getClass().getClassLoader()
                .getResourceAsStream("templates/ordersetting_template.xlsx");

        if (resourceAsStream == null) {
            throw new RuntimeException("Excel 模板文件未找到，请检查路径是否正确！");
        }

        try (
                XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
                ServletOutputStream outputStream = response.getOutputStream()
        ) {
            XSSFSheet sheet = excel.getSheet("预约设置模板");
            if (sheet == null) {
                throw new RuntimeException("Excel 中不存在名为 '预约设置模板' 的工作表");
            }

            List<OrderSettingVO> list = orderSettingMapper.selectAllReservation();

            int rowNum = 1; // 从第二行开始写入数据（索引从0开始）

            for (OrderSettingVO orderSettingVO : list) {
                XSSFRow row = sheet.getRow(rowNum);
                if (row == null) {
                    row = sheet.createRow(rowNum); // 如果行不存在，就创建
                }

                // 写入第一列：预约日期
                setCellValueAsString(row, 0, Optional.ofNullable(orderSettingVO.getOrderDate()).map(Object::toString).orElse(""));
                // 写入第二列：预约人数
                setCellValueAsString(row, 1, Optional.ofNullable(orderSettingVO.getNumber()-orderSettingVO.getReservations()).map(Object::toString).orElse(""));

                rowNum++;
            }

            // 输出 Excel 到客户端
            excel.write(outputStream);

        } catch (IOException e) {
            throw new RuntimeException("导出 Excel 出错", e);
        }
    }


    /**
     * 安全地将字符串写入单元格
     */
    private void setCellValueAsString(XSSFRow row, int cellIndex, String value) {
        XSSFCell cell = row.getCell(cellIndex);
        if (cell == null) {
            cell = row.createCell(cellIndex);
        }
        cell.setCellValue(value);
    }

    @Override
    public void editNumberByOrderDate(EditNumberByOrderDateDTO dto) {
        OrderSetting orderSetting = new OrderSetting();
        orderSetting.setNumber(Integer.parseInt(dto.getNumber()));
        orderSetting.setOrderDate(java.sql.Date.valueOf(dto.getOrderDate()));
        orderSettingMapper.editNumberByOrderDate(orderSetting);

    }

    @Override
    public List<OrderSetting> getOrderSettingByMonth(String month) {
        // 解析字符串为 YearMonth
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-M"));
        // 获取当月第一天和最后一天
        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();
        Date firstDay = java.sql.Date.valueOf(startDate);
        Date lastDay = java.sql.Date.valueOf(endDate);

        return orderSettingMapper.getOrderSettingByMonth(firstDay, lastDay);    }

    @Override
    public void upload(MultipartFile templateFile) {
        if (templateFile == null || templateFile.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        // 指定模板文件存储路径
        File storageDir = new File("D:\\study\\code\\idea\\ideaProject\\bxg-health-parent_dev\\bxg-health-backend\\src\\main\\resources\\templates\\new_templates");

        // 如果目标目录不存在，则创建目录
        if (!storageDir.exists()) {
            storageDir.mkdirs(); // 创建多级目录
        }

        // 获取上传的原始文件名
        String originalFilename = templateFile.getOriginalFilename();
        if (originalFilename == null || originalFilename.isBlank()) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        // 构建目标文件对象
        File destFile = new File(storageDir, originalFilename);

        try {
            // 将上传的文件保存到指定位置
            templateFile.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }

}